package server

import (
	"context"
	"git.huoys.com/middle-business/xds/internal/model"
	v2 "github.com/envoyproxy/go-control-plane/envoy/api/v2"
	"github.com/envoyproxy/go-control-plane/pkg/cache"
	"google.golang.org/grpc/peer"
	"log"
	"time"
)

func (s *Server) FetchEndpoints(ctx context.Context, in *v2.DiscoveryRequest) (*v2.DiscoveryResponse, error) {
	resp :=  &v2.DiscoveryResponse{VersionInfo: model.VERSION, TypeUrl: cache.EndpointType}
	resources, err := redisDao.LoadResources(ctx, in.ResourceNames)
	if err != nil {
		return nil, err
	}
	resp.Resources = resources
	return resp, nil
}

func (s *Server) StreamEndpoints(stream v2.EndpointDiscoveryService_StreamEndpointsServer) error {

	clientPeer, ok := peer.FromContext(stream.Context())
	clientIP := "unknown"
	if ok {
		clientIP = clientPeer.Addr.String()
	}
	log.Printf("[%s] -------------- Starting a %s stream from %s ------------------\n", model.SUBSCRIBE_EDS, model.SUBSCRIBE_EDS, clientIP)

	for {
		req, err := stream.Recv()
		if err != nil {
			log.Println("[StreamEndpoints] Recv fail, msg: ", err.Error())
			return err
		}
		log.Printf("[StreamEndpoints] recv version %s ResourceNames %s TypeUrl %s", req.VersionInfo, req.ResourceNames, req.TypeUrl)
		resp :=  &v2.DiscoveryResponse{VersionInfo: model.VERSION, TypeUrl: cache.EndpointType}
		resources := s.LoadEndpoints(context.Background(), req.ResourceNames)
		if err != nil {
			log.Println("[StreamEndpoints] LoadResources fail, msg: ", err.Error())
			continue
		}
		resp.Resources = resources
		log.Println("[StreamEndpoints] resp: ", resp)
		stream.Send(resp)
		time.Sleep(time.Second * 30)
	}
}

/*func (s *Server) StreamEndpoints(stream v2.EndpointDiscoveryService_StreamEndpointsServer) error {

	clientPeer, ok := peer.FromContext(stream.Context())
	clientIP := "unknown"
	if ok {
		clientIP = clientPeer.Addr.String()
	}
	log.Printf("[%s] -------------- Starting a %s stream from %s ------------------\n", model.SUBSCRIBE_EDS, model.SUBSCRIBE_EDS, clientIP)

	for {
		req, err := stream.Recv()
		if err != nil {
			log.Println("[StreamEndpoints] Recv fail, msg: ", err.Error())
			return err
		}
		log.Printf("[StreamEndpoints] recv version %s ResourceNames %s", req.VersionInfo, req.ResourceNames)
		resp :=  &v2.DiscoveryResponse{VersionInfo: model.VERSION, TypeUrl: cache.EndpointType}
		resources, err := redisDao.LoadResources(context.Background(), req.ResourceNames)
		if err != nil {
			log.Println("[StreamEndpoints] LoadResources fail, msg: ", err.Error())
			continue
		}
		resp.Resources = resources
		log.Println("[StreamEndpoints] resp: ", resp)
		stream.Send(resp)
		time.Sleep(time.Second * 30)
	}
}
*/